package cc.eddic.practice.concurrency;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class LogParserTyqImpl implements LogParser {
    LogItemParserTyqImpl logItemParserTyq = new LogItemParserTyqImpl();

    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        //新建map接收结果
        Map<String, List<LogItem>> map = new HashMap<>();
        //新建List存储log文件
        List<File> filesList = new ArrayList<>();
        //获取文件夹里的所有log文件
        fileResult(new File(folderName), filesList);
        filesList.stream().filter(file -> file.getName().endsWith(".log"))
                .forEach(f -> {
                    List<LogItem> logItemList = readList(f.getPath()).stream().map(filestring -> logItemParserTyq.parse(filestring)).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
                    map.put(f.getName(), logItemList);
                });
        return map;
    }

    private void fileResult(File file, List<File> filesList) {
        //获取文件夹下的所有文件
        val files = file.listFiles();
        if (files == null) {
            return;
        }
        for (val f : files) {
            if (f.isDirectory()) {
                fileResult(f, filesList);
            } else filesList.add(f);
        }
    }

    //读每一行
    public Stream<String> read(String textFileName) {
        try {
            val p = Paths.get(textFileName);
            return Files.lines(p);
        } catch (IOException e) {
            if (log.isDebugEnabled()) log.debug("{}", textFileName);
            return null;
        }
    }

    //读每一行后变成List
    public List<String> readList(String textFileName) {
        return read(textFileName).collect(Collectors.toList());
    }
}
